package com.zxl.template;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.Toast;

import com.kinggrid.iappoffice.IAppOffice;
import com.zxl.template.constant.constant;
import com.zxl.zlibrary.http.OkHttpUtils;
import com.zxl.zlibrary.http.callback.FileCallBack;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;


/*
 * @created by LoveLing on 2018/11/29
 * @emil 1079112877@qq.com
 * description:
 */
public class TestActivity extends AppCompatActivity implements constant {
    private static final String TAG = "TestActivity";


    private static final String COPY_RIGHT = "SxD/phFsuhBWZSmMVtSjKZmm/c/3zSMrkV2Bbj5tznSkEVZmTwJv0wwMmH/+p6wLiUHbjadYueX9v51H9GgnjUhmNW1xPkB++KQqSv/VKLDsR8V6RvNmv0xyTLOrQoGzAT81iKFYb1SZ/Zera1cjGwQSq79AcI/N/6DgBIfpnlwiEiP2am/4w4+38lfUELaNFry8HbpbpTqV4sqXN1WpeJ7CHHwcDBnMVj8djMthFaapMFm/i6swvGEQ2JoygFU38558QhLaX/Jr1koWwK15kEmTvMG/nhvTilibTVNrCtS1VzVwUlmsSQF90/OYTdIhuI7ZTJqU764j1aPQnpiJKCoW/T3lHnHSqUG9ekm19Ty6lZhbc0wZsYY7F8fGE4DHZs4YOxNd7fnxKM4Dd4Klf1+OBmeDcECRDSxKMJbBZX2hOjA9xBaBPEEybxot0XBztGIYfNWOY83ltjqKjeToDSIzRqZYYUbAtzuYjy8C+3Ix04ev8Hm/as8N+FyWSdRWDRk0QFLuqgyKytzjbVWa9W3+KjjXk4eWYscdbEPDzss=";
    @BindView(R.id.btn)
    Button btn;
    @BindView(R.id.web)
    WebView web;
    /*
     * 文件的绝对路径
     */
    private String fileName;

    /*
     * SD卡根目录
     */
    private static final String SDCARD_ROOT_PATH = Environment.getExternalStorageDirectory().getPath();
    private String file = "http://132.232.4.78/receipt/download?attach_id=8d98b0c357764a45be2e143ad43eefae";

    private IAppOffice mAppOffice;

    private static GetReceiver getRec;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.aty_test);
        ButterKnife.bind(this);

        requestPermissions();
        verifyStoragePermissions();

        registerIntentFilters();

        //设置需要打开的目标文件;
        fileName = SDCARD_ROOT_PATH + "/123.doc";


//        web.loadUrl("https://222.221.245.174:6443");
        web.loadUrl("https://www.baidu.com");


        //初始化iAppOffice, 注：先设置授权码，后调用init();
        mAppOffice = new IAppOffice(this);
        mAppOffice.setCopyRight(COPY_RIGHT);
        mAppOffice.init();


        OkHttpUtils//
                .get()//
                .url(file)//
                .build()//
                .execute(new FileCallBack(Environment.getExternalStorageDirectory().getAbsolutePath(), "123.docx") {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        Log.e(TAG, "onError :" + e.getMessage());
                    }

                    @Override
                    public void onResponse(File file, int i) {
                        Toast.makeText(TestActivity.this, file.getAbsolutePath(), Toast.LENGTH_LONG).show();
                        Log.e(TAG, "onResponse :" + file.getAbsolutePath());


                    }

                    @Override
                    public File parseNetworkResponse(Response response, int id) throws Exception {
                        response.headers("");

                        return super.parseNetworkResponse(response, id);
                    }
                });

        findViewById(R.id.btn).setOnClickListener(v -> {
            if (mAppOffice.isWPSInstalled()) {
                mAppOffice.setFileName(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/123.docx");
                mAppOffice.setIsReviseMode(true);
                mAppOffice.setUseMethod2(true);
                mAppOffice.appOpen(true);

            } else {
                Toast.makeText(TestActivity.this, "请安装WPS专业版！", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public void registerIntentFilters() {
        if (getRec == null) {
            IntentFilter backFilter = new IntentFilter();
            backFilter.addAction(BROADCAST_BACK_DOWN);
            IntentFilter homeFilter = new IntentFilter();
            homeFilter.addAction(BROADCAST_HOME_DOWN);
            IntentFilter saveFilter = new IntentFilter();
            saveFilter.addAction(BROADCAST_FILE_SAVE);
            IntentFilter closeFilter = new IntentFilter();
            closeFilter.addAction(BROADCAST_FILE_CLOSE);
            IntentFilter notFindFilter = new IntentFilter();
            notFindFilter.addAction("com.kinggrid.notfind.office");
            IntentFilter savePicFilter = new IntentFilter();
            savePicFilter.addAction(BROADCAST_FILE_SAVE_PIC);
            IntentFilter showHandwriteFilter = new IntentFilter();
            showHandwriteFilter.addAction("com.kinggrid.iappoffice.showHandwrite");
            IntentFilter homekeyFilter = new IntentFilter();
            homekeyFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            IntentFilter saveAsPDFFilter = new IntentFilter();
            saveAsPDFFilter.addAction(BROADCAST_FILE_SAVEAS_PDF);
            IntentFilter openEndFilter = new IntentFilter();
            openEndFilter.addAction(BROADCAST_FILE_OPEN_END);

            getRec = new GetReceiver();

            registerReceiver(getRec, backFilter);
            registerReceiver(getRec, homeFilter);
            registerReceiver(getRec, saveFilter);
            registerReceiver(getRec, closeFilter);
            registerReceiver(getRec, notFindFilter);
            registerReceiver(getRec, savePicFilter);
            registerReceiver(getRec, showHandwriteFilter);
            registerReceiver(getRec, homekeyFilter);
            registerReceiver(getRec, saveAsPDFFilter);
            registerReceiver(getRec, openEndFilter);
        }
    }

    public class GetReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (BROADCAST_BACK_DOWN.equals(intent.getAction())) {
                Log.d(TAG, "key back down");
            } else if (BROADCAST_HOME_DOWN.equals(intent.getAction())) {
                Log.d(TAG, "key home down");
            } else if (BROADCAST_FILE_SAVE.equals(intent.getAction())) {
                Log.d(TAG, BROADCAST_FILE_SAVE + " : file save");
            } else if (BROADCAST_FILE_CLOSE.equals(intent.getAction())) {
                Log.d(TAG, BROADCAST_FILE_CLOSE + " : file close");
            } else if ("com.kinggrid.notfind.office".equals(intent.getAction())) {
                Log.d(TAG, "wps office not find");
            } else if (BROADCAST_FILE_SAVE_PIC.equals(intent.getAction())) {
                Log.d(TAG, "office save pic over");
            } else if (BROADCAST_FILE_SAVEAS_PDF.equals(intent.getAction())) {
                Log.d(TAG, "office save as pdf over");
            } else if (BROADCAST_FILE_SAVEAS.equals(intent.getAction())) {

            }
        }
    }


    private void requestPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                // Permission has not been granted and must be
                // requested.

                if (shouldShowRequestPermissionRationale(Manifest.permission.READ_PHONE_STATE)) {

                }

                requestPermissions(
                        new String[]{Manifest.permission.READ_PHONE_STATE},
                        1);


            } else {

            }
        }
    }

    //动态获取内存存储权限
    public void verifyStoragePermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                // Permission has not been granted and must be
                // requested.

                if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                }

                requestPermissions(
                        new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                        1);


            } else {


            }
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        Log.v(TAG, "stop");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.v(TAG, "restart");

    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "demo destroy");
        mAppOffice.unInit();
        unregisterReceiver(getRec);
        super.onDestroy();
    }


}
